import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/king/king_rank_logic.dart';
import 'package:sports_new/entity/king/king_rank_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/pick/items/avator_label.dart';
import 'package:sports_new/view/pick/items/banner_scaffold.dart';
import 'package:sports_new/widgets/base/qkd_indicator.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';
import '../../utils/utils.dart';
import '../../widgets/base/qkd_text.dart';
import '../../widgets/loading/loading_widget.dart';
import 'items/king_rule_item.dart';

class KingRankPage extends StatefulWidget {
  const KingRankPage({super.key});

  @override
  State<KingRankPage> createState() => _KingRankPageState();
}

class _KingRankPageState extends State<KingRankPage> with TickerProviderStateMixin{
  final KingRankLogic logic = Get.put(KingRankLogic());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<KingRankLogic>(
      builder: (logic) {
        return BannerScaffold(
          type: "king_rank_${logic.rankType}",
          needScroll: true,
          titleFade: true,
          title: logic.rankName,
          aboveWidget: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                KingRuleItem(title: "活动规则", button: "king_${logic.rankType}_tip"),
                Container(height: 9)
              ]
          ),
          body: (physics) => LoadingWidget<bool>(
            isLoading: logic.rankList.every((element) => element == null),
            data: logic.dayList?.length == 0,
            child: () => Container(
              color: Colours.white,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      QkdText(logic.rankName,
                        fontSize: 16,
                        color: Colours.text292D32,
                        fontWeight: FontWeight.w500),
                      const Spacer(),
                      QkdText("球票结算时间：${logic.updateTime}",
                        fontSize: 12
                      )
                    ],
                  ).paddingOnly(top: 12,left: 16,right: 16),
                  rectScrollBar().paddingOnly(top: 12,left: 16,right: 16),
                  Expanded(
                    child: TabBarView(
                      controller: logic.tabController,
                      children: List.generate(logic.rankList.length, (index) =>
                        LoadingWidget<bool>(
                          isLoading: logic.rankList[index] == null,
                          data: (logic.rankList[index]?.length ?? 0) <= 1,
                          noData: const NoDataWidget(tip: "暂无排名，快去预测吧"),
                          child: () => rankList(logic.rankList[index]
                          ).paddingSymmetric(horizontal: 16)
                        )
                      )
                    ),
                  )
                ]
              ),
            ),
          ),
        );
      }
    );
  }

  Widget rankList(List<KingRankItem>? entity){
    var list = entity?.sublist(1,entity.length);
    return Column(
      children: [
        userItem(entity?[0],-1).paddingOnly(top: 12),
        DefaultTextStyle(
          style: const TextStyle(
            fontSize: 12,color: Colours.grey66),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                flex: 2,
                child: QkdText("排名").center),
              Expanded(
                flex: 5,
                child: QkdText("用户昵称").paddingOnly(left: 48)),
              Expanded(
                flex: 2,
                child: QkdText("球票").center)
            ]
          )
        ).paddingOnly(top: 16,bottom: 10),
        Expanded(child: MediaQuery.removePadding(
          context: context,
          removeTop: true,
          child: EasyRefresh.builder(
            controller: logic.refreshController,
            footer: Styles.refreshFooter(
              position: IndicatorPosition.locator,
              noMoreText: "没有更多用户"
            ),
            onLoad: logic.updateData,
            childBuilder: (context,physics) {
              return CustomScrollView(
                physics: physics,
                slivers: [
                  SliverList.list(
                    children: List.generate(list?.length ?? 0, (index) {
                      return userItem(list?[index],index);
                    }),
                  ),
                  const FooterLocator.sliver()
                ],
              );
            }
          ),
        ))
      ],
    );
  }

  Widget userItem(KingRankItem? item,int index){
    List<String> icon = ["1","2","3"];
    Color color = Colours.white;
    if(item?.sort == "1") color = Colours.redFFEEEE;
    if(item?.sort == "2") color = Colours.goldFFF7E0;
    if(item?.sort == "3") color = Colours.blueEFF7F9;
    if(index == -1) color = Colours.greyF8;
    return Container(
      height: 64,
      margin: EdgeInsets.only(bottom: index<3 && index>=0?8:0),
      decoration: BoxDecoration(
        color: color,
        border: index<3? null:
          const Border(bottom: BorderSide(color: Colours.greyEE,width: 0.5)),
        borderRadius: index<3? BorderRadius.circular(8):null),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          if(icon.contains(item?.sort))
          Expanded(
            flex: 2,
            child: Image.asset(
              width: 32,height: 32,
              Utils.getImgPath("icon_rank_${item?.sort}.png"))),
          if(!icon.contains(item?.sort))
          Expanded(
            flex: 2,
            child: QkdText(item?.sort.toString() ?? "",
              fontSize: 12,color: Colours.grey66
            ).center),
          Expanded(
              flex: 5,
              child: AvatarLabel.tag(
                  type: 0,
                  needJump: (){},
                  avatarUrl: item?.logo ?? "",
                  name: item?.name ?? "",
                  nameWeight: FontWeight.w500,
                  tagList: [],
                  id: item?.userId)),
          Expanded(
            flex: 2,
            child: QkdText("${item?.score ?? ""}球票",
              color: Colours.grey66
            ).center)
        ]
      ),
    );
  }

  Widget rectScrollBar() {
    return TabBar(
      physics: const ClampingScrollPhysics(),
        tabs: List.generate(logic.dayList?.length ?? 0, (index) => Container(
            padding: const EdgeInsets.symmetric(horizontal: 17),
            height: 40,
            decoration: BoxDecoration(
              // color: logic.tabIndex == index?Colours.main:Colours.transparent,
              // border: Border.all(
              //   strokeAlign: BorderSide.strokeAlignCenter,
              //   color: logic.tabIndex == index?Colours.transparent:Colours.greyEE,width: 1
              // ),
              borderRadius: BorderRadius.circular(8)
            ),
            child: QkdText(logic.dayList?[index] ?? "").center)),
        controller: logic.tabController,
        indicator: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          color: Colours.main,
          border: Border.all(color: Colours.greyEE,width: 0.5)
        ),
        isScrollable: true,
        indicatorWeight: 0,
        labelPadding: const EdgeInsets.only(right: 8),
        indicatorSize: TabBarIndicatorSize.label,
        labelColor: Colours.white,
        unselectedLabelColor: Colours.grey66,
        labelStyle: const TextStyle(fontSize: 14),
        unselectedLabelStyle: const TextStyle(fontSize: 14)
    );
  }
}
